package com.znow.admin.system.security.util;

import com.znow.admin.system.security.model.dto.PermissionsTreeDTO;
import com.znow.admin.system.security.model.dto.SysUserDetailsDTO;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.context.SecurityContext;
import org.springframework.security.core.context.SecurityContextHolder;

import java.util.Collection;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author PC
 * @date 2022/12/14
 */
public class SecurityUtils {

    /**
     * 获取用户
     *
     * @return {@link SysUserDetailsDTO}
     */
    public final static SysUserDetailsDTO getUser() {
        final SecurityContext context = SecurityContextHolder.getContext();
        if (context == null) {

        }
        final Authentication authentication = context.getAuthentication();
        if (authentication == null) {

        }
        final Object principal = authentication.getPrincipal();
        if (principal == null) {

        }
        return (SysUserDetailsDTO) principal;
    }

    public final static Collection<? extends GrantedAuthority> getAuthorities() {
        final SysUserDetailsDTO user = getUser();
        return user.getAuthorities();
    }


    /**
     * 得到用户的权限
     *
     * @return {@link List}<{@link String}>
     */
    public final static List<String> getAuthoritiesWithString() {
        final SysUserDetailsDTO user = getUser();
        final List<PermissionsTreeDTO> authorities = (List<PermissionsTreeDTO>) user.getAuthorities();
        return authorities.stream().map(GrantedAuthority::getAuthority).collect(Collectors.toList());
    }

    /**
     * 获取用户ID
     *
     * @return {@link Long}
     */
    public final static Long getUserId() {
        final SysUserDetailsDTO user = getUser();
        return user.getUserId();
    }
}
